2.2 服务提供者

首先说明一下,为了便于讲解,本节之后,如无特殊说明,均是以单点的Eureka进行讲解的。

服务提供者和服务消费者

下面这张表格,简单描述了服务提供者/消费者是什么:

名词 概念
服务提供者 服务的被调用方(即:为其他服务提供服务的服务)
服务消费者 服务的调用方(即:依赖其他服务的服务)

服务提供者代码示例

这是一个稍微有点复杂的程序。我们使用spring-data-jpa操作h2数据库,同时将该服务注册到注册中心Eureka中。

  • 创建一个Maven工程,并在pom.xml中添加如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>microservice-provider-user</artifactId>
  <packaging>jar</packaging>

  <parent>
    <groupId>com.itmuch.cloud</groupId>
    <artifactId>spring-cloud-microservice-study</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>

  <dependencies>
    <!-- 添加Eureka的依赖 -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
  </dependencies>
</project>
  • 配置文件:application.yml
server:
  port: 8000
spring:
  application:
    name: microservice-provider-user    # 项目名称尽量用小写
  jpa:
    generate-ddl: false
    show-sql: true
    hibernate:
      ddl-auto: none
  datasource:                           # 指定数据源
    platform: h2                        # 指定数据源类型
    schema: classpath:schema.sql        # 指定h2数据库的建表脚本
    data: classpath:data.sql            # 指定h2数据库的insert脚本
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
    com.itmuch.youran.persistence: ERROR
eureka:
  client:
    serviceUrl:
      defaultZone: http://discovery:8761/eureka/    # 指定注册中心的地址
  instance:
    preferIpAddress: true
  • 建表语句:schema.sql
drop table user if exists;
create table user (id bigint generated by default as identity, username varchar(255), age int, primary key (id));
  • 插库语句:data.sql
insert into user (id, username, age) values (1,'Tom',12);
insert into user (id, username, age) values (2,'Jerry', 23);
insert into user (id, username, age) values (3,'Reno', 44);
insert into user (id, username, age) values (4,'Josh', 55);
  • DAO:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
  • Controller:
/**
 * 作用:
 * ① 测试服务实例的相关内容
 * ② 为后来的服务做提供
 * @author eacdy
 */
@RestController
public class UserController {
  @Autowired
  private DiscoveryClient discoveryClient;
  @Autowired
  private UserRepository userRepository;

  /**
   * 注:@GetMapping("/{id}")是spring 4.3的新注解等价于:
   * @RequestMapping(value = "/id", method = RequestMethod.GET)
   * 类似的注解还有@PostMapping等等
   * @param id
   * @return user信息
   */
  @GetMapping("/{id}")
  public User findById(@PathVariable Long id) {
    User findOne = this.userRepository.findOne(id);
    return findOne;
  }

  /**
   * 本地服务实例的信息
   * @return
   */
  @GetMapping("/instance-info")
  public ServiceInstance showInfo() {
    ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
    return localServiceInstance;
  }
}
  • 实体类:
@Entity
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  @Column
  private String username;
  @Column
  private Integer age;
  ...
  // getters and setters
}
  • 编写Spring Boot启动程序,通过@EnableDiscoveryClient注解,即可将microservice-provider-user服务注册到Eureka上面去
@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {
  public static void main(String[] args) {
    SpringApplication.run(UserApplication.class, args);
  }
}

至此,代码编写完成。

测试

我们依次启动Eureka服务和microservice-provider-user服务。

访问:http://localhost:8761,如下图。我们会发现microservice-provider-user服务已经被注册到了Eureka上面了。

user-service服务注册到Eureka上

访问:http://localhost:8000/instance-info,返回结果:

{
    "host": "192.168.0.59",
    "port": 8000,
    "metadata": {},
    "uri": "http://192.168.0.59:8000",
    "secure": false,
    "serviceId": "microservice-provider-user"
}

访问:http://discovery:8000/1,返回结果:

{
    "id": 1,
    "username": "Tom",
    "age": 12
}

服务注册到高可用Eureka

如果Eureka 是高可用的,那么各个微服务配置只需要将defaultZone 改为如下即可:

eureka:
  client:
    serviceUrl:
      defaultZone: http://peer1:8761/eureka/,http://peer2:8762/eureka

代码地址(任选其一)

http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-provider-user https://github.com/eacdy/spring-cloud-study/tree/master/microservice-provider-user

results matching ""

    No results matching ""